import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import Main from '@/layouts/main'
import OverView from '@/views/over-view'
import { useUserStore } from '@/stores/user'
import { AuthOperationType, WhiteRoutes } from './const'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    // 导航栏、头部、内容布局
    {
      path: '/',
      name: 'main',
      redirect: '/over-view',
      component: Main,
      children: [
        {
          path: '/over-view',
          name: 'overView',
          component: OverView,
          meta: {
            title: '概览',
          },
        },
        {
          path: '/ai-agent',
          name: 'aiAgent',
          component: () => import('@/views/ai-agent'),
          meta: {
            title: '概览',
          },
        },
      ],
    },
    // 导航栏 + 内容布局（可以自定义头部）
    {
      path: '/sub',
      name: 'sub',
      component: () => import('@/layouts/sub'),
      children: [
        {
          path: '/agent-detail/:id',
          name: 'agentDetail',
          props: (route) => ({
            id: route.params.id,
          }),
          component: () => import('@/views/ai-agent/detail'),
        },
      ],
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login'),
      props: (route) => ({
        type: route.query.type,
      }),
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/login'),
      props: (route) => ({
        type: route.query.type,
      }),
    },
    {
      path: '/404',
      name: '404',
      component: () => import('@/views/404/index'),
    },
  ],
})

router.beforeEach((to, _, next) => {
  const user = useUserStore()
  if (!user.hasToken) {
    if (!WhiteRoutes.includes(to.name)) {
      router.push({
        path: '/login',
        query: {
          type: AuthOperationType.Login,
        },
      })
    }
  }
  next()
})

export default router
